propsage.namespace("prestige.adsControl");

prestige.adsControl.review = (function($, ui){
	var abbrs = [
	{
		"to": "yrs", 
		"regex":new RegExp("years", 'i'), 
		"score":10
	},

	{
		"to": "Fty", 
		"regex":new RegExp("factory", 'i')
	},

	{
		"to": "Gnd", 
		"regex":new RegExp("ground", 'i')
	},

	{
		"to": "blk", 
		"regex":new RegExp("block", 'i')
	},

	{
		"to": "rms", 
		"regex":new RegExp("rooms", 'i')
	},

	{
		"to": "PENTHSE", 
		"regex":new RegExp("penthouse", 'i')
	},

	{
		"to": "reno", 
		"regex":new RegExp("renovation", 'i')
	},

	{
		"to": "immed", 
		"regex":new RegExp("immediately|immediate", 'i')
	},

	{
		"to": "flr", 
		"regex":new RegExp("floor", 'i')
	},

	{
		"to": "agt", 
		"regex":new RegExp("agent", 'i')
	},

	{
		"to": "furn", 
		"regex":new RegExp("furnished", 'i')
	},

	{
		"to": "bdrm", 
		"regex":new RegExp("bedroom", 'i')
	},

	{
		"to": "Biz", 
		"regex":new RegExp("business", 'i')
	},

	{
		"to": "Pk", 
		"regex":new RegExp("park", 'i')
	},

	{
		"to": "King", 
		"regex":new RegExp("king george", 'i')
	},
	];
	
	var badWords = [];	
	var badWordsFound = [];
	
	function initComponents()
	{
		onCheckBoxChange();
		
		ui.doAjax('POST', baseUrl + '/adsControl/ajaxLoadFilters', {
			agency_id: agencyId
		}, onFiltersLoadSuccess);
	}

	
	function initEventHandlers() 
	{ 
		$('#Advertisement_approval_status input:radio').change(onCheckBoxChange);
		$("#Advertisement_ad_message").on('keydown change', onTextAdKeyDown);
		
	}
	
	function onTextAdKeyDown(event)
	{
		var $input = $(this); 
		var unique;
		var sentenceNoBreaks
		
		if($input.val() == ''){
			$("#rating-percentage").html('');
		}	
		window.setTimeout(function(){
			var sentence = formatSentence($input.val(), event.which);
			$("#adsim span").html(sentence);
			sentenceNoBreaks = $input.val().split(/[\s\n]/).join(' ');
			filterSentence(sentenceNoBreaks);
			unique = distinct(badWordsFound);
			$("#badWords span").html(unique.join(' '));
		}, 20);
	}
	
	function nl2br (str, is_xhtml) {
		var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br/>' : '<br>';
		return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
	}
	
	function findAbbreviation(words)
	{	
		for (var i in words) {	
			var word = words[i];			
			if (word == "") {
				continue;
			} else {	
				for (var j in abbrs) {
					var abbr = abbrs[j];

					var matches = word.match(abbr.regex);

					if (matches != null) {
						words[i] = word.replace(matches[0], abbr.to);
						break;
					}
				}
			}
		}

		return words;
	}
	
	function capitalizefirst3words(words)
	{
		var maxWords = 3;

		if (words != null && words.length < 3) {
			maxWords = words.length;
		}

		if (words != null) {
			for (var i = 0; i < maxWords; i++) {
				var word = words[i];
				var $span = $(word);
				var spanText = $span.text();

				spanText = '<b>' + spanText.toUpperCase() + '</b>';

				$span.html(spanText);					

				words[i] = $('<div/>').append($span).html();
			}
		}

		return words;			
	}
	
	function formatSentence(sentence, key)
	{
		// add spans
		var original = sentence;
		
		sentence = nl2br(sentence);
		var words = sentence.split(/\s/);
		
		// split up <br/>
		for (var i in words) {
			if (words[i].indexOf('<br/>') !== -1 && words[i] != '<br/>') {
				var parts = words[i].split('<br/>');
				parts[1] = '<br/>';
				var args = [parseInt(i), 1];
				args = args.concat(parts)
				
				words.splice.apply(words, args);
				
			}
		}
		
		sentence = '<span>' + words.join("</span> <span>") + '</span>';
		
		var words = sentence.split(" ");
		words = findAbbreviation(words);
		
		words=capitalizefirst3words(words);
		
		sentence = words.join(" ");

		return sentence;
	}
	
	function filterSentence(sentence) 
	{
		var totalScore = 0;
		badWordsFound = [];
		var score = 0;
		for (var j in badWords) {
						
			var phraseToTest = badWords[j].phrase.toLowerCase();
			var phraseLength = phraseToTest.length;
						
			var startIndex = sentence.toLowerCase().indexOf(phraseToTest);
						
			if (startIndex != -1) {
				var endIndex = startIndex + phraseLength;
				var subString = sentence.substring(startIndex, endIndex);
							
				score =  parseInt(badWords[j].score);
				
		
				totalScore +=score;
							
				var color = colorcode(score);
							
				var $span = $("<span>"+subString+"</span>");
				$span.addClass(color);
				var $html = $('<div/>').append($span).html();
								
				badWordsFound.push($html);
							
				continue;
			}
		}
		
		$("#rating-percentage").html(totalScore);
		if(totalScore >= 100){
			$("#rating-percentage").css('color','red');
		} else {
			$("#rating-percentage").css('color','');
		}
		$("#Advertisement_rejection_score").val(totalScore);
		
	}
	
	function onCheckBoxChange()
	{
		var $radio_buttons = $('#Advertisement_approval_status input:radio');
		if($radio_buttons.filter(':checked').length > 0){
			$('#update-status').addClass('green').removeAttr('disabled');
		} else {
			$('#update-status').removeClass('green').attr("disabled", "disabled");
		}
	}
	
	
	
	function onFiltersLoadSuccess(response)
	{
		var totalScore = 0;
		var score = 0;
		
		badWords = response.data;

//		var sentence = $("#Advertisement_ad_message").val();
//		
//		if(badWords){
//			for (var j in badWords) {
//				var phraseToTest = badWords[j].phrase.toLowerCase();
//				var phraseLength = phraseToTest.length;
//						
//				var startIndex = sentence.toLowerCase().indexOf(phraseToTest);
//						
//				if (startIndex != -1) {
//					var endIndex = startIndex + phraseLength;
//					var subString = sentence.substring(startIndex, endIndex);
//							
//					score =  parseInt(badWords[j].score);
//					
//					var color = colorcode(score);
//							
//					var $span = $("<span>"+subString+"</span>");
//					$span.addClass(color);
//					var $html = $('<div/>').append($span).html();
//								
//					badWordsFound.push($html);
//				}
//			}
//		}
//		
//		var unique = distinct(badWordsFound);
//		$("#badWords span").html(unique.join(' '));
		
		if($('#Advertisement_ad_message').val() !== ''){
			$('#Advertisement_ad_message').trigger('change');
		}
		
	}
	
	function distinct(anArray)
	{
		var result = [];
		$.each(anArray, function(i,v){
			if ($.inArray(v, result) == -1) result.push(v);
		});
		return result;
	}
	
	function colorcode(score)
	{
		switch (true){
			case (score > 70):
				return "high"
				break;
			case (score > 30):
				return "medium"
				break; 
			default:
				return "low"
				break; 
		}
	}
	
	$(document).ready(function(){
		initEventHandlers();
		initComponents();
		
	});
	
}(jQuery, propsage.ui));